/**
 * 弹幕系统后端API接口
 * 统一管理所有与后端的数据交互
 * 支持灵活切换不同的后端服务
 */

import type { BarrageItem } from './types'

// 接口配置类型
export interface ApiEndpoints {
  // 弹幕相关接口
  barrages: {
    getAll: string           // 获取所有弹幕
    getByVideo: string       // 根据视频ID获取弹幕 (需要替换 {videoId})
    send: string             // 发送弹幕
    sendBatch: string        // 批量发送弹幕
    delete: string           // 删除弹幕 (需要替换 {id})
    stats: string            // 弹幕统计
  }
  // 视频相关接口
  videos: {
    getAll: string           // 获取所有视频
    getById: string          // 根据ID获取视频 (需要替换 {id})
    upload: string           // 上传视频信息
    update: string           // 更新视频信息 (需要替换 {id})
    delete: string           // 删除视频 (需要替换 {id})
    search: string           // 搜索视频
    categories: string       // 获取分类
    stats: string            // 视频统计 (需要替换 {id})
  }
  // 系统接口
  system: {
    health: string           // 健康检查
    config: string           // 系统配置
  }
}

// 预定义的接口配置
export const API_PRESETS = {
  // 默认 JSON Server 配置
  jsonServer: {
    baseUrl: 'http://localhost:3001',
    endpoints: {
      barrages: {
        getAll: '/barrages',
        getByVideo: '/barrages?videoId={videoId}',
        send: '/barrages',
        sendBatch: '/barrages/batch',
        delete: '/barrages/{id}',
        stats: '/barrages/stats'
      },
      videos: {
        getAll: '/videos',
        getById: '/videos/{id}',
        upload: '/videos',
        update: '/videos/{id}',
        delete: '/videos/{id}',
        search: '/videos/search',
        categories: '/videos/categories',
        stats: '/videos/{id}/stats'
      },
      system: {
        health: '/health',
        config: '/config'
      }
    }
  } as { baseUrl: string; endpoints: ApiEndpoints },

  // 自定义后端配置示例
  customBackend: {
    baseUrl: 'https://your-api.com/api/v1',
    endpoints: {
      barrages: {
        getAll: '/danmu/list',
        getByVideo: '/danmu/video/{videoId}',
        send: '/danmu/send',
        sendBatch: '/danmu/batch',
        delete: '/danmu/{id}',
        stats: '/danmu/stats'
      },
      videos: {
        getAll: '/video/list',
        getById: '/video/{id}',
        upload: '/video/upload',
        update: '/video/{id}',
        delete: '/video/{id}',
        search: '/video/search',
        categories: '/video/categories',
        stats: '/video/{id}/stats'
      },
      system: {
        health: '/system/health',
        config: '/system/config'
      }
    }
  } as { baseUrl: string; endpoints: ApiEndpoints },

  // 企业级后端配置示例
  enterprise: {
    baseUrl: 'https://enterprise-api.com/v2',
    endpoints: {
      barrages: {
        getAll: '/comments/all',
        getByVideo: '/comments/by-video/{videoId}',
        send: '/comments/create',
        sendBatch: '/comments/batch-create',
        delete: '/comments/{id}',
        stats: '/analytics/comments'
      },
      videos: {
        getAll: '/media/videos',
        getById: '/media/videos/{id}',
        upload: '/media/upload',
        update: '/media/videos/{id}',
        delete: '/media/videos/{id}',
        search: '/media/search',
        categories: '/media/categories',
        stats: '/analytics/videos/{id}'
      },
      system: {
        health: '/status',
        config: '/settings'
      }
    }
  } as { baseUrl: string; endpoints: ApiEndpoints }
}

// 当前API配置
export class ApiConfig {
  private static instance: ApiConfig
  private baseUrl: string
  private endpoints: ApiEndpoints
  private headers: Record<string, string>
  private timeout: number

  private constructor() {
    // 默认使用 JSON Server 配置
    const defaultConfig = API_PRESETS.jsonServer
    this.baseUrl = defaultConfig.baseUrl
    this.endpoints = defaultConfig.endpoints
    this.headers = {
      'Content-Type': 'application/json'
    }
    this.timeout = 10000
  }

  static getInstance(): ApiConfig {
    if (!ApiConfig.instance) {
      ApiConfig.instance = new ApiConfig()
    }
    return ApiConfig.instance
  }

  /**
   * 切换API配置预设
   */
  usePreset(presetName: keyof typeof API_PRESETS): void {
    const preset = API_PRESETS[presetName]
    if (!preset) {
      throw new Error(`Unknown API preset: ${presetName}`)
    }
    this.baseUrl = preset.baseUrl
    this.endpoints = preset.endpoints
    console.log(`🔄 API配置已切换到: ${presetName}`)
  }

  /**
   * 自定义API配置
   */
  useCustomConfig(baseUrl: string, endpoints: ApiEndpoints): void {
    this.baseUrl = baseUrl
    this.endpoints = endpoints
    console.log(`🔄 API配置已切换到自定义: ${baseUrl}`)
  }

  /**
   * 设置请求头
   */
  setHeaders(headers: Record<string, string>): void {
    this.headers = { ...this.headers, ...headers }
  }

  /**
   * 设置认证Token
   */
  setAuthToken(token: string): void {
    this.headers['Authorization'] = `Bearer ${token}`
  }

  /**
   * 设置超时时间
   */
  setTimeout(timeout: number): void {
    this.timeout = timeout
  }

  /**
   * 构建完整URL
   */
  buildUrl(endpoint: string, params?: Record<string, string>): string {
    let url = `${this.baseUrl}${endpoint}`
    
    // 替换路径参数
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        url = url.replace(`{${key}}`, encodeURIComponent(value))
      })
    }
    
    return url
  }

  /**
   * 获取配置信息
   */
  getConfig() {
    return {
      baseUrl: this.baseUrl,
      endpoints: this.endpoints,
      headers: this.headers,
      timeout: this.timeout
    }
  }
}

// API响应类型
export interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: string
}

// 弹幕数据类型（扩展基础类型）
export interface BarrageData extends Omit<BarrageItem, 'id'> {
  id?: string
  videoId: string
  time: number
  timestamp: string
  user?: string
  ip?: string
  device?: string
}

// 视频相关数据类型
export interface VideoData {
  id: string
  name: string
  url: string
  duration?: number
  thumbnail?: string
  uploadTime?: string
  barrageCount?: number
  // 新增字段
  category?: string
  description?: string
  tags?: string[]
  size?: number // 文件大小（字节）
  format?: string // 视频格式 (mp4, webm, etc.)
  resolution?: string // 分辨率 (1920x1080, etc.)
  viewCount?: number // 播放次数
  likeCount?: number // 点赞数
  isLocal?: boolean // 是否为本地文件
  status?: 'active' | 'processing' | 'error' // 视频状态
  metadata?: {
    fps?: number // 帧率
    bitrate?: number // 比特率
    codec?: string // 编码格式
    aspectRatio?: string // 宽高比
  }
}

// 统计数据类型
export interface BarrageStats {
  totalCount: number
  activeUsers: number
  peakTime: string
  popularWords: Array<{ word: string; count: number }>
}

/**
 * 通用HTTP请求封装
 */
class ApiClient {
  private config: ApiConfig

  constructor() {
    this.config = ApiConfig.getInstance()
  }

  /**
   * 发送HTTP请求
   */
  private async request<T>(
    endpoint: string,
    options: RequestInit = {},
    pathParams?: Record<string, string>
  ): Promise<ApiResponse<T>> {
    const url = this.config.buildUrl(endpoint, pathParams)
    const controller = new AbortController()
    const { timeout, headers } = this.config.getConfig()
    
    // 设置请求超时
    const timeoutId = setTimeout(() => controller.abort(), timeout)

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
        headers: {
          ...headers,
          ...options.headers,
        },
      })

      clearTimeout(timeoutId)

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      const data = await response.json()
      return {
        success: true,
        data,
      }
    } catch (error) {
      clearTimeout(timeoutId)
      
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      console.error(`API请求失败 [${endpoint}]:`, errorMessage)
      
      return {
        success: false,
        error: errorMessage,
      }
    }
  }

  /**
   * GET请求
   */
  async get<T>(endpoint: string, pathParams?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'GET' }, pathParams)
  }

  /**
   * POST请求
   */
  async post<T>(endpoint: string, data: any, pathParams?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    }, pathParams)
  }

  /**
   * PUT请求
   */
  async put<T>(endpoint: string, data: any, pathParams?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    }, pathParams)
  }

  /**
   * DELETE请求
   */
  async delete<T>(endpoint: string, pathParams?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'DELETE' }, pathParams)
  }
}

// 创建API客户端实例
const apiClient = new ApiClient()

/**
 * 弹幕相关API
 */
export const BarrageAPI = {
  /**
   * 获取指定视频的所有弹幕
   */
  async getBarragesByVideo(videoId: string): Promise<ApiResponse<BarrageData[]>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.barrages.getByVideo
    return apiClient.get<BarrageData[]>(endpoint, { videoId })
  },

  /**
   * 获取所有弹幕
   */
  async getAllBarrages(): Promise<ApiResponse<BarrageData[]>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.barrages.getAll
    return apiClient.get<BarrageData[]>(endpoint)
  },

  /**
   * 发送新弹幕
   */
  async sendBarrage(barrage: Omit<BarrageData, 'id' | 'timestamp'>): Promise<ApiResponse<BarrageData>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.barrages.send
    const barrageWithTimestamp = {
      ...barrage,
      timestamp: new Date().toISOString(),
    }
    return apiClient.post<BarrageData>(endpoint, barrageWithTimestamp)
  },

  /**
   * 批量发送弹幕（用于压力测试等场景）
   */
  async sendBatchBarrages(barrages: Omit<BarrageData, 'id' | 'timestamp'>[]): Promise<ApiResponse<BarrageData[]>> {
    const config = ApiConfig.getInstance()
    const batchEndpoint = config.getConfig().endpoints.barrages.sendBatch
    const barragesWithTimestamp = barrages.map(barrage => ({
      ...barrage,
      timestamp: new Date().toISOString(),
    }))
    
    // 尝试批量接口
    try {
      return await apiClient.post<BarrageData[]>(batchEndpoint, barragesWithTimestamp)
    } catch {
      // 否则逐个发送
      const results: BarrageData[] = []
      for (const barrage of barragesWithTimestamp) {
        const result = await this.sendBarrage(barrage)
        if (result.success && result.data) {
          results.push(result.data)
        }
      }
      return { success: true, data: results }
    }
  },

  /**
   * 删除弹幕
   */
  async deleteBarrage(barrageId: string): Promise<ApiResponse<void>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.barrages.delete
    return apiClient.delete<void>(endpoint, { id: barrageId })
  },

  /**
   * 获取弹幕统计信息
   */
  async getBarrageStats(videoId?: string): Promise<ApiResponse<BarrageStats>> {
    const config = ApiConfig.getInstance()
    let endpoint = config.getConfig().endpoints.barrages.stats
    
    // 如果有videoId参数，添加查询参数
    if (videoId) {
      endpoint += `?videoId=${videoId}`
    }
    
    return apiClient.get<BarrageStats>(endpoint)
  },
}

/**
 * 视频相关API
 */
export const VideoAPI = {
  /**
   * 获取所有视频列表
   */
  async getAllVideos(): Promise<ApiResponse<VideoData[]>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.getAll
    return apiClient.get<VideoData[]>(endpoint)
  },

  /**
   * 获取视频详情
   */
  async getVideoById(videoId: string): Promise<ApiResponse<VideoData>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.getById
    return apiClient.get<VideoData>(endpoint, { id: videoId })
  },

  /**
   * 搜索视频
   */
  async searchVideos(query: string, filters?: {
    category?: string
    minDuration?: number
    maxDuration?: number
    sortBy?: 'name' | 'uploadTime' | 'duration' | 'barrageCount' | 'viewCount'
    sortOrder?: 'asc' | 'desc'
  }): Promise<ApiResponse<VideoData[]>> {
    const config = ApiConfig.getInstance()
    let endpoint = config.getConfig().endpoints.videos.search
    
    const params = new URLSearchParams({ q: query })
    if (filters) {
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined) {
          params.append(key, value.toString())
        }
      })
    }
    
    endpoint += `?${params.toString()}`
    return apiClient.get<VideoData[]>(endpoint)
  },

  /**
   * 获取视频分类列表
   */
  async getVideoCategories(): Promise<ApiResponse<Array<{ name: string; count: number }>>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.categories
    return apiClient.get<Array<{ name: string; count: number }>>(endpoint)
  },

  /**
   * 获取视频统计信息
   */
  async getVideoStats(videoId: string): Promise<ApiResponse<{
    viewCount: number
    barrageCount: number
    likeCount: number
    duration: number
    uploadTime: string
    lastViewTime?: string
  }>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.stats
    return apiClient.get<{
      viewCount: number
      barrageCount: number
      likeCount: number
      duration: number
      uploadTime: string
      lastViewTime?: string
    }>(endpoint, { id: videoId })
  },

  /**
   * 上传视频信息
   */
  async uploadVideoInfo(video: Omit<VideoData, 'id' | 'uploadTime'>): Promise<ApiResponse<VideoData>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.upload
    const videoWithTimestamp = {
      ...video,
      uploadTime: new Date().toISOString(),
    }
    return apiClient.post<VideoData>(endpoint, videoWithTimestamp)
  },

  /**
   * 更新视频信息
   */
  async updateVideo(videoId: string, updates: Partial<VideoData>): Promise<ApiResponse<VideoData>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.update
    return apiClient.put<VideoData>(endpoint, updates, { id: videoId })
  },

  /**
   * 删除视频
   */
  async deleteVideo(videoId: string): Promise<ApiResponse<void>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.videos.delete
    return apiClient.delete<void>(endpoint, { id: videoId })
  },

  // 保留一些便捷方法，但简化实现
  async getPopularVideos(_limit: number = 10): Promise<ApiResponse<VideoData[]>> {
    return this.searchVideos('', { sortBy: 'barrageCount', sortOrder: 'desc' })
  },

  async getLatestVideos(_limit: number = 10): Promise<ApiResponse<VideoData[]>> {
    return this.searchVideos('', { sortBy: 'uploadTime', sortOrder: 'desc' })
  },
}

/**
 * 系统相关API
 */
export const SystemAPI = {
  /**
   * 检查服务器状态
   */
  async checkServerStatus(): Promise<ApiResponse<{ status: 'online' | 'offline'; version?: string }>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.system.health
    return apiClient.get<{ status: 'online' | 'offline'; version?: string }>(endpoint)
  },

  /**
   * 获取系统配置
   */
  async getSystemConfig(): Promise<ApiResponse<Record<string, any>>> {
    const config = ApiConfig.getInstance()
    const endpoint = config.getConfig().endpoints.system.config
    return apiClient.get<Record<string, any>>(endpoint)
  },
}

/**
 * 快速配置API的便捷函数
 */
export const ApiManager = {
  /**
   * 切换到预设配置
   */
  switchToPreset(presetName: keyof typeof API_PRESETS): void {
    const config = ApiConfig.getInstance()
    config.usePreset(presetName)
  },

  /**
   * 切换到自定义配置
   */
  switchToCustom(baseUrl: string, endpoints: ApiEndpoints): void {
    const config = ApiConfig.getInstance()
    config.useCustomConfig(baseUrl, endpoints)
  },

  /**
   * 设置认证信息
   */
  setAuth(token: string): void {
    const config = ApiConfig.getInstance()
    config.setAuthToken(token)
  },

  /**
   * 设置自定义请求头
   */
  setHeaders(headers: Record<string, string>): void {
    const config = ApiConfig.getInstance()
    config.setHeaders(headers)
  },

  /**
   * 获取当前配置
   */
  getCurrentConfig() {
    const config = ApiConfig.getInstance()
    return config.getConfig()
  },

  /**
   * 测试API连接
   */
  async testConnection(): Promise<{ success: boolean; message: string }> {
    try {
      const result = await SystemAPI.checkServerStatus()
      if (result.success) {
        return { success: true, message: '连接成功' }
      } else {
        return { success: false, message: result.error || '连接失败' }
      }
    } catch (error) {
      return { 
        success: false, 
        message: `连接错误: ${error instanceof Error ? error.message : '未知错误'}` 
      }
    }
  },
}

/**
 * 便捷的组合API函数
 */
export const CombinedAPI = {
  /**
   * 初始化应用数据（获取视频列表和弹幕数据）
   */
  async initializeApp(videoId?: string): Promise<{
    videos: VideoData[]
    barrages: BarrageData[]
    serverStatus: 'online' | 'offline'
  }> {
    const [videosResult, barragesResult, statusResult] = await Promise.allSettled([
      VideoAPI.getAllVideos(),
      videoId ? BarrageAPI.getBarragesByVideo(videoId) : BarrageAPI.getAllBarrages(),
      SystemAPI.checkServerStatus(),
    ])

    return {
      videos: videosResult.status === 'fulfilled' && videosResult.value.success 
        ? videosResult.value.data || [] 
        : [],
      barrages: barragesResult.status === 'fulfilled' && barragesResult.value.success 
        ? barragesResult.value.data || [] 
        : [],
      serverStatus: statusResult.status === 'fulfilled' && statusResult.value.success 
        ? statusResult.value.data?.status || 'offline' 
        : 'offline',
    }
  },

  /**
   * 切换视频时的数据加载
   */
  async switchVideo(videoId: string): Promise<{
    video: VideoData | null
    barrages: BarrageData[]
  }> {
    const [videoResult, barragesResult] = await Promise.allSettled([
      VideoAPI.getVideoById(videoId),
      BarrageAPI.getBarragesByVideo(videoId),
    ])

    return {
      video: videoResult.status === 'fulfilled' && videoResult.value.success 
        ? videoResult.value.data || null 
        : null,
      barrages: barragesResult.status === 'fulfilled' && barragesResult.value.success 
        ? barragesResult.value.data || [] 
        : [],
    }
  },
}

// 默认导出主要API对象
export default {
  // 核心API
  BarrageAPI,
  VideoAPI,
  SystemAPI,
  CombinedAPI,
  
  // 配置管理
  ApiManager,
  ApiConfig,
  API_PRESETS,
}
